//
// ProcessExecutor
//
// Copyright (C) jextra.net.
//
//  This file is part of the Crack build system.
//
//  The Crack build system is free software; you can redistribute it 
//  and/or modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  The Crack build system is distributed in the hope that it will be 
//  useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with the Crack build system; if not, write to the Free
//  Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
//  02111-1307 USA.
//

package net.jextra.crack.tool;

import java.io.*;
import java.util.*;

/**
 * Wrapper class to ProcessBuilder, and consequently to a Process. This class takes care of consuming System.err
 * properly to avoid deadlock.
 */
public class ProcessExecutor
{
    // ============================================================
    // Fields
    // ============================================================

    private ProcessBuilder processBuilder;
    private OutputStream outStream;
    private OutputStream errStream;

    private Process process;
    private StreamGobbler outThread;
    private StreamGobbler errThread;

    private int exitStatus;

    // ============================================================
    // Constructors
    // ============================================================

    public ProcessExecutor()
    {
        processBuilder = new ProcessBuilder();

        // By default output goes to System.out and erros go to System.err.
        outStream = System.out;
        errStream = System.err;

        Runtime.getRuntime().addShutdownHook( new ShutdownThread() );
    }

    // ============================================================
    // Methods
    // ============================================================

    public void setOutputStream( OutputStream outStream )
    {
        this.outStream = outStream;
    }

    public void setErrStream( OutputStream errStream )
    {
        this.errStream = errStream;
    }

    /**
     * @see ProcessBuilder.directory( File )
     */
    public void setDirectory( File dir )
    {
        processBuilder.directory( dir );
    }

    /**
     * @see ProcessBuilder.directory()
     */
    public File getDirectory()
    {
        return processBuilder.directory();
    }

    /**
     * @see ProcessBuilder.environment()
     */
    public Map<String, String> getEnvironment()
    {
        return processBuilder.environment();
    }

    public int execute( List<String> args )
        throws Exception
    {
        processBuilder.command( args );
        execute();
        return exitStatus;
    }

    public int execute( String ... args )
        throws Exception
    {
        processBuilder.command( args );
        execute();
        return exitStatus;
    }

    public Process getProcess()
    {
        return process;
    }

    public int getExitStatus()
    {
        return exitStatus;
    }

    // ----------
    // protected
    // ----------

    protected void execute()
        throws Exception
    {
        exitStatus = 0;

        //
        // Create the actual process.
        //
        process = processBuilder.start();

        //
        // Setup output "gobblers".
        //
        outThread = new StreamGobbler( process.getInputStream(), outStream );
        outThread.start();

        errThread = new StreamGobbler( process.getErrorStream(), errStream );
        errThread.start();

        //
        // Wait for the process to finish and the output streams to finish.
        //
        exitStatus = process.waitFor();
        while ( outThread.isBusy() || errThread.isBusy() )
        {
            Thread.sleep( 100 );
        }

        // Help out GC.
        process = null;
        outThread = null;
        errThread = null;
    }

    protected void destroy()
    {
        if ( process == null )
        {
            return;
        }

        process.destroy();
    }

    // ============================================================
    // Inner Classes
    // ============================================================

    private class StreamGobbler extends Thread
    {
        private InputStream _inputStream;
        private OutputStream _outputStream;
        private boolean _busy;

        StreamGobbler( InputStream inputStream, OutputStream outputStream )
        {
            _inputStream = inputStream;
            _outputStream = outputStream;
        }

        @Override
        public void run()
        {
            try
            {
                _busy = true;
                BufferedReader br = new BufferedReader( new InputStreamReader( _inputStream ) );
                OutputStreamWriter bw = _outputStream == null ? null : new OutputStreamWriter( _outputStream );

                String lineRead = null;
                while ( ( lineRead = br.readLine() ) != null )
                {
                    if ( bw != null )
                    {
                        bw.write( lineRead );
                        bw.write( "\n" );
                        bw.flush();
                    }
                }
                bw.flush();
            }
            catch ( Exception ex )
            {
                // Don't know what else to do here, just print the stack trace.
                ex.printStackTrace();
            }
            finally
            {
                _busy = false;
            }
        }
        
        public boolean isBusy()
        {
            return _busy;
        }
    }

    private class ShutdownThread extends Thread
    {
        @Override
        public void run()
        {
            ProcessExecutor.this.destroy();
        }
    }
}
